<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
    <!-- 导航栏 -->
    <nav class="bg-white/80 backdrop-blur-sm shadow-lg border-b border-blue-100">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <router-link to="/" class="text-xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
              知识图谱管理器
            </router-link>
          </div>
          <div class="flex items-center space-x-4">
            <router-link to="/" class="text-gray-600 hover:text-blue-600 transition-colors duration-200">
              首页
            </router-link>
            <router-link to="/graph-query" class="text-gray-600 hover:text-purple-600 transition-colors duration-200">
              查询图谱
            </router-link>
            <span class="text-blue-600 font-medium bg-blue-100 px-3 py-1 rounded-full">转换器</span>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容 -->
    <div class="max-w-7xl mx-auto py-2 px-4 sm:px-6 lg:px-8">
      <div class="py-2">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <!-- 左侧：Markdown转换器 -->
          <div class="bg-white/90 backdrop-blur-sm overflow-hidden shadow-xl rounded-xl border border-blue-100">
            <div class="px-4 py-5 sm:p-6">
              <h3 class="text-lg leading-6 font-medium bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent mb-4">
                📄 Markdown 文件转换
              </h3>
              
              <!-- 文件上传区域 -->
              <div class="mb-6">
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  选择 Markdown 文件
                </label>
                <div 
                  class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-dashed rounded-md transition-colors"
                  :class="isDragOver ? 'border-blue-400 bg-gradient-to-br from-blue-50 to-indigo-50' : 'border-gray-300 hover:border-blue-300 hover:bg-gradient-to-br hover:from-blue-50/50 hover:to-indigo-50/50'"
                  @drop="handleDrop"
                  @dragover="handleDragOver"
                  @dragleave="handleDragLeave"
                >
                  <div class="space-y-1 text-center">
                    <svg class="mx-auto h-6 w-6 text-blue-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                      <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    </svg>
                    <div class="flex text-sm text-gray-600">
                      <label for="file-upload" class="relative cursor-pointer bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-3 py-1 rounded-md font-medium hover:from-blue-700 hover:to-indigo-700 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-blue-500 transition-all duration-200">
                        <span>上传文件</span>
                        <input 
                          id="file-upload" 
                          ref="fileInput"
                          name="file-upload" 
                          type="file" 
                          class="sr-only" 
                          multiple 
                          accept=".md"
                          @change="handleFileSelect"
                        >
                      </label>
                      <p class="pl-1">或拖拽到此处</p>
                    </div>
                    <p class="text-xs text-gray-500">
                      支持 .md 格式，可选择多个文件
                    </p>
                  </div>
                </div>
                
                <!-- 已选择的文件列表 -->
                <div v-if="selectedFiles.length > 0" class="mt-4">
                  <h4 class="text-sm font-medium bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent mb-2">📁 已选择的文件 ({{ selectedFiles.length }})</h4>
                  <div class="space-y-2">
                    <div 
                      v-for="(file, index) in selectedFiles" 
                      :key="index"
                      class="flex items-center justify-between bg-gradient-to-r from-blue-50 to-indigo-50 px-3 py-2 rounded-lg border border-blue-100 shadow-sm hover:shadow-md transition-all duration-200"
                    >
                      <span class="text-sm text-gray-700">{{ file.name }}</span>
                      <button 
                        @click="removeFile(index)"
                        class="text-red-500 hover:text-red-700 hover:bg-red-50 p-1 rounded-full transition-all duration-200"
                      >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 层级选择 -->
              <div class="mb-6">
                <h4 class="text-md font-medium bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent mb-3">🎯 层级配置</h4>
                <div class="space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-purple-700 mb-2">📊 选择知识层级</label>
                    <select 
                      v-model="selectedLevel"
                      class="mt-1 block w-full border-gray-300 rounded-lg shadow-sm focus:ring-purple-500 focus:border-purple-500 focus:bg-purple-50/30 transition-all duration-200"
                    >
                      <option value="basic">基础层</option>
                      <option value="intermediate">过渡层</option>
                      <option value="advanced">进阶层</option>
                      <option value="expert">高阶层</option>
                    </select>
                    <p class="mt-1 text-xs text-gray-500">
                      选择的层级将应用于所有上传的文件
                    </p>
                  </div>
                  
                  <div>
                    <label class="block text-sm font-medium text-purple-700 mb-2">🎚️ 难度系数</label>
                    <div class="flex items-center space-x-3">
                      <button 
                        @click="decreaseDifficulty"
                        :disabled="difficultyLevel <= 1"
                        class="w-8 h-8 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-full hover:from-purple-600 hover:to-pink-600 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center justify-center"
                      >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"></path>
                        </svg>
                      </button>
                      <div class="flex-1">
                        <input 
                          v-model.number="difficultyLevel"
                          type="number"
                          min="1"
                          max="10"
                          class="w-full text-center border-gray-300 rounded-lg shadow-sm focus:ring-purple-500 focus:border-purple-500 focus:bg-purple-50/30 transition-all duration-200"
                        >
                      </div>
                      <button 
                        @click="increaseDifficulty"
                        :disabled="difficultyLevel >= 10"
                        class="w-8 h-8 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-full hover:from-purple-600 hover:to-pink-600 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center justify-center"
                      >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                        </svg>
                      </button>
                    </div>
                    <p class="mt-1 text-xs text-gray-500">
                      设置知识点的难度系数 (1-10)，默认为 1
                    </p>
                  </div>
                </div>
              </div>

              <!-- Neo4j 配置 -->
              <div class="mb-6">
                <h4 class="text-md font-medium bg-gradient-to-r from-green-600 to-teal-600 bg-clip-text text-transparent mb-3">🗄️ Neo4j 数据库配置</h4>
                <div class="grid grid-cols-1 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-green-700">🔗 数据库 URI</label>
                    <input 
                      v-model="neo4jConfig.uri"
                      type="text" 
                      class="mt-1 block w-full border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500 focus:bg-green-50/30 transition-all duration-200" 
                      placeholder="bolt://localhost:7687"
                    >
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-green-700">👤 用户名</label>
                    <input 
                      v-model="neo4jConfig.username"
                      type="text" 
                      class="mt-1 block w-full border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500 focus:bg-green-50/30 transition-all duration-200" 
                      placeholder="neo4j"
                    >
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-green-700">🔐 密码</label>
                    <input 
                      v-model="neo4jConfig.password"
                      type="password" 
                      class="mt-1 block w-full border-gray-300 rounded-lg shadow-sm focus:ring-green-500 focus:border-green-500 focus:bg-green-50/30 transition-all duration-200" 
                      placeholder="请输入密码"
                    >
                  </div>
                  <div class="mt-4">
                    <button 
                      @click="testNeo4jConnection"
                      :disabled="isTestingConnection"
                      class="w-full bg-gradient-to-r from-green-500 to-teal-500 text-white px-3 py-2 rounded-lg hover:from-green-600 hover:to-teal-600 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 text-sm"
                    >
                      <span v-if="isTestingConnection">测试连接中...</span>
                      <span v-else>🔍 测试连接</span>
                    </button>
                    <div v-if="connectionTestResult" class="mt-2 text-sm">
                      <div v-if="connectionTestResult.success" class="text-green-600 bg-green-50 p-2 rounded">
                        ✅ {{ connectionTestResult.message }}
                      </div>
                      <div v-else class="text-red-600 bg-red-50 p-2 rounded">
                        ❌ {{ connectionTestResult.message }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 导入策略选择 -->
              <div class="mb-6">
                <h4 class="text-md font-medium bg-gradient-to-r from-orange-600 to-red-600 bg-clip-text text-transparent mb-3">⚙️ 导入策略</h4>
                <div class="space-y-3">
                  <div class="flex items-center space-x-3">
                    <input 
                      id="incremental"
                      v-model="importMode"
                      type="radio"
                      value="incremental"
                      class="h-4 w-4 text-orange-600 focus:ring-orange-500 border-gray-300"
                    >
                    <label for="incremental" class="flex-1 text-sm text-gray-700">
                      <span class="font-medium text-orange-600">🔄 增量导入</span>
                      <p class="text-xs text-gray-500 mt-1">保留现有数据，仅添加或更新新内容（推荐）</p>
                    </label>
                  </div>
                  <div class="flex items-center space-x-3">
                    <input 
                      id="rebuild"
                      v-model="importMode"
                      type="radio"
                      value="rebuild"
                      class="h-4 w-4 text-red-600 focus:ring-red-500 border-gray-300"
                    >
                    <label for="rebuild" class="flex-1 text-sm text-gray-700">
                      <span class="font-medium text-red-600">🗑️ 清空重建</span>
                      <p class="text-xs text-gray-500 mt-1">删除所有现有数据，重新导入（谨慎使用）</p>
                    </label>
                  </div>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="flex space-x-3">
                <button 
                  @click="convertFiles"
                  :disabled="selectedFiles.length === 0 || converterStore.isConverting"
                  class="flex-1 bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-4 py-2 rounded-lg hover:from-blue-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-105 transition-all duration-200 shadow-lg"
                >
                  <span v-if="converterStore.isConverting">转换中...</span>
                  <span v-else>转换为 JSON</span>
                </button>
                <button 
                  @click="importToNeo4j"
                  :disabled="!hasConvertedData || converterStore.isImporting"
                  class="flex-1 bg-gradient-to-r from-green-600 to-emerald-600 text-white px-4 py-2 rounded-lg hover:from-green-700 hover:to-emerald-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-105 transition-all duration-200 shadow-lg"
                >
                  <span v-if="converterStore.isImporting">导入中...</span>
                  <span v-else>导入到 Neo4j</span>
                </button>
              </div>
            </div>
          </div>

          <!-- 右侧：进度和结果 -->
          <div class="space-y-6 flex flex-col h-full">
            <!-- 转换进度 -->
            <div class="bg-white/90 backdrop-blur-sm overflow-hidden shadow-xl rounded-xl border border-purple-100">
              <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium bg-gradient-to-r from-purple-600 to-pink-600 bg-clip-text text-transparent mb-4">
                  📊 转换进度
                </h3>
                <div class="space-y-4">
                  <div>
                    <div class="flex justify-between text-sm font-medium text-gray-700">
                      <span>文件解析</span>
                      <span>{{ Math.round(converterStore.conversionProgress) }}%</span>
                    </div>
                    <div class="mt-1 bg-gray-200 rounded-full h-2 overflow-hidden">
                      <div 
                        class="bg-gradient-to-r from-blue-500 to-indigo-500 h-2 rounded-full transition-all duration-300 shadow-sm" 
                        :style="{ width: converterStore.conversionProgress + '%' }"
                      ></div>
                    </div>
                  </div>
                  <div>
                    <div class="flex justify-between text-sm font-medium text-gray-700">
                      <span>数据导入</span>
                      <span>{{ Math.round(converterStore.importProgress) }}%</span>
                    </div>
                    <div class="mt-1 bg-gray-200 rounded-full h-2 overflow-hidden">
                      <div 
                        class="bg-gradient-to-r from-green-500 to-emerald-500 h-2 rounded-full transition-all duration-300 shadow-sm" 
                        :style="{ width: converterStore.importProgress + '%' }"
                      ></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 结果预览 -->
            <div class="bg-white/90 backdrop-blur-sm overflow-hidden shadow-xl rounded-xl border border-orange-100 flex-1 flex flex-col">
              <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium bg-gradient-to-r from-orange-600 to-red-600 bg-clip-text text-transparent mb-4">
                  🎯 结果预览
                </h3>
                <div class="bg-gradient-to-br from-gray-50 to-blue-50/30 rounded-xl p-4 flex-1 overflow-y-auto border border-gray-100">
                  <div v-if="!hasConvertedData" class="text-gray-500 text-center mt-20">
                    转换完成后将在此显示结果
                  </div>
                  <div v-else class="space-y-4">
                    <!-- 统计信息 -->
                    <div class="grid grid-cols-2 gap-4 text-sm">
                      <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-3 rounded-lg border border-blue-200 shadow-sm">
                        <div class="font-medium text-blue-700">📚 主题</div>
                        <div class="text-2xl font-bold text-blue-600">{{ converterStore.knowledgeGraph.topics.length }}</div>
                      </div>
                      <div class="bg-gradient-to-br from-green-50 to-green-100 p-3 rounded-lg border border-green-200 shadow-sm">
                        <div class="font-medium text-green-700">🌿 子主题</div>
                        <div class="text-2xl font-bold text-green-600">{{ converterStore.knowledgeGraph.subtopics.length }}</div>
                      </div>
                      <div class="bg-gradient-to-br from-orange-50 to-orange-100 p-3 rounded-lg border border-orange-200 shadow-sm">
                        <div class="font-medium text-orange-700">💡 知识点</div>
                        <div class="text-2xl font-bold text-orange-600">{{ converterStore.knowledgeGraph.knowledge_points.length }}</div>
                      </div>
                      <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-3 rounded-lg border border-purple-200 shadow-sm">
                        <div class="font-medium text-purple-700">🔮 概念</div>
                        <div class="text-2xl font-bold text-purple-600">{{ converterStore.knowledgeGraph.concepts.length }}</div>
                      </div>
                    </div>
                    
                    <!-- 导入结果 -->
                    <div v-if="importResult" class="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-lg p-3 shadow-sm">
                      <div class="flex">
                        <svg class="w-5 h-5 text-green-400" fill="currentColor" viewBox="0 0 20 20" style="width: 1.25rem; height: 1.25rem;">
                          <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                        </svg>
                        <div class="ml-3">
                          <h3 class="text-sm font-medium text-green-800">导入成功</h3>
                          <div class="mt-2 text-sm text-green-700">
                            <p>{{ importResult.message }}</p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useConverterStore } from '@/stores/converter'

const converterStore = useConverterStore()

// 响应式数据
const selectedFiles = ref<File[]>([])
const isDragOver = ref(false)
const fileInput = ref<HTMLInputElement>()
const importResult = ref<any>(null)
const selectedLevel = ref('basic') // 默认选择基础层
const difficultyLevel = ref(1) // 默认难度系数为1
const isTestingConnection = ref(false) // 测试连接状态
const connectionTestResult = ref<{success: boolean, message: string} | null>(null) // 连接测试结果
const importMode = ref('incremental') // 导入策略：incremental（增量）或 rebuild（重建）

// Neo4j 配置
const neo4jConfig = ref({
  uri: 'bolt://49.235.155.102:7687',
  username: 'neo4j',
  password: '123qweasd!'
})

// 计算属性
const hasConvertedData = computed(() => {
  return converterStore.knowledgeGraph.topics.length > 0 ||
         converterStore.knowledgeGraph.subtopics.length > 0 ||
         converterStore.knowledgeGraph.knowledge_points.length > 0 ||
         converterStore.knowledgeGraph.concepts.length > 0
})

// 文件处理方法
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files) {
    addFiles(Array.from(target.files))
  }
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
  
  if (event.dataTransfer?.files) {
    const files = Array.from(event.dataTransfer.files).filter(file => file.name.endsWith('.md'))
    addFiles(files)
  }
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
}

const addFiles = (files: File[]) => {
  const newFiles = files.filter(file => 
    file.name.endsWith('.md') && 
    !selectedFiles.value.some(existing => existing.name === file.name)
  )
  selectedFiles.value.push(...newFiles)
}

const removeFile = (index: number) => {
  selectedFiles.value.splice(index, 1)
}

// 难度控制方法
const increaseDifficulty = () => {
  if (difficultyLevel.value < 10) {
    difficultyLevel.value++
  }
}

const decreaseDifficulty = () => {
  if (difficultyLevel.value > 1) {
    difficultyLevel.value--
  }
}

// Neo4j 连接测试方法
const testNeo4jConnection = async () => {
  isTestingConnection.value = true
  connectionTestResult.value = null
  
  try {
    const response = await fetch('/api/neo4j/test', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        neo4jConfig: neo4jConfig.value
      })
    })
    
    const result = await response.json()
    
    if (response.ok) {
      connectionTestResult.value = {
        success: true,
        message: result.message || 'Neo4j 连接测试成功'
      }
    } else {
      connectionTestResult.value = {
        success: false,
        message: result.message || '连接测试失败'
      }
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    connectionTestResult.value = {
      success: false,
      message: '无法连接到后端服务，请确保后端API服务正在运行'
    }
  } finally {
    isTestingConnection.value = false
  }
}

// 转换和导入方法
const convertFiles = async () => {
  if (selectedFiles.value.length === 0) return
  
  try {
    importResult.value = null
    await converterStore.convertFiles(selectedFiles.value, selectedLevel.value, difficultyLevel.value)
    console.log('转换完成:', converterStore.knowledgeGraph)
  } catch (error) {
    console.error('转换失败:', error)
    alert('转换失败: ' + (error as Error).message)
  }
}

const importToNeo4j = async () => {
  if (!hasConvertedData.value) return
  
  try {
    const result = await converterStore.importToNeo4j(
      converterStore.knowledgeGraph,
      {
        uri: neo4jConfig.value.uri,
        username: neo4jConfig.value.username,
        password: neo4jConfig.value.password
      },
      importMode.value
    )
    importResult.value = result
    console.log('导入完成:', result)
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error as Error).message)
  }
}
</script>